package com.offcn.oauth.service.impl;

import com.offcn.oauth.entity.AuthToken;
import com.offcn.oauth.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Override
    public AuthToken login(String username, String password, String clientId, String clientSecret) {
        ServiceInstance instance = loadBalancerClient.choose("USER-AUTH");
        if (instance == null) {
            throw new RuntimeException("没有找到对应的服务");
        }

        // 访问路径  localhost:10000/oauth/token
        String path = instance.getUri().toString() + "/oauth/token";

        // 请求头
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        String str = clientId + ":" + clientSecret;
        headers.add("Authorization","Basic " + new String(Base64Utils.encode(str.getBytes())));

        // 请求体
        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        param.add("grant_type","password");
        param.add("username",username);
        param.add("password",password);


        // 实现远程调用
        ResponseEntity<Map> response = restTemplate.exchange(path, HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(param, headers), Map.class);
        Map responseMap = response.getBody();
        if (responseMap == null || responseMap.get("access_token") == null || responseMap.get("refresh_token") == null ){
            throw new RuntimeException("创建令牌失败");
        }
        return new AuthToken((String)responseMap.get("access_token"),(String)responseMap.get("refresh_token"),(String)responseMap.get("jti"));
    }
}
